package isquirrel;

import isquirrel.beans.Log;
import isquirrel.beans.User;
import isquirrel.util.HibernateUtil;

import java.math.BigInteger;

public class Logger {
	
	public static void log(User user, String label) {
		Log log = new Log();
		log.setUserID(user.getUserID());
		log.setLabel(label);
		log.setUsers(getUsersCount().longValue());
		log.setFriends(getFriendsCount(user).longValue());
		log.setLiked(getLikedCount(user).longValue());
		log.setInterests(getInterestsCount(user).longValue());
		log.setStaticRecs(getStaticURLsCount(user).longValue());
		log.setDynamicRecs(getDynamicURLsCount(user).longValue());
		HibernateUtil.getSession().save(log);
	}
	
	public static BigInteger getUsersCount() {
		return (BigInteger) HibernateUtil.getSession().createSQLQuery("SELECT count(user_id) FROM users").uniqueResult();
	}
	
	public static BigInteger getFriendsCount(User user) {
		return (BigInteger) HibernateUtil.getSession()
		.createSQLQuery("SELECT count(friend_id) FROM user_friends WHERE user_id = ?")
		.setLong(0, user.getUserID())
		.uniqueResult();
	}
	
	public static BigInteger getInterestsCount(User user) {
		return (BigInteger) HibernateUtil.getSession()
		.createSQLQuery("SELECT count(interest_id) FROM interests WHERE user_id = ?")
		.setLong(0, user.getUserID())
		.uniqueResult();
	}
	
	public static BigInteger getLikedCount(User user) {
		return (BigInteger) HibernateUtil.getSession()
		.createSQLQuery("SELECT count(url_id) FROM urls WHERE user_id = ? AND liked= ?")
		.setLong(0, user.getUserID())
		.setBoolean(1, true)
		.uniqueResult();
	}
	
	public static BigInteger getStaticURLsCount(User user) {
		return (BigInteger) HibernateUtil.getSession()
		.createSQLQuery("SELECT count(url_id) FROM urls WHERE user_id = ? AND source = ?")
		.setLong(0, user.getUserID())
		.setString(1, "static")
		.uniqueResult();
	}
	
	public static BigInteger getDynamicURLsCount(User user) {
		return (BigInteger) HibernateUtil.getSession()
		.createSQLQuery("SELECT count(url_id) FROM urls WHERE user_id = ? AND source = ?")
		.setLong(0, user.getUserID())
		.setString(1, "dynamic")
		.uniqueResult();
	}
	
	

}
